package com.huichenghe.xinlvsh01.slide;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huichenghe.xinlvsh01.Adapter.RemindCustomRecyclerAdapter;
import com.huichenghe.xinlvsh01.Ble.BleDataForCustomRemind;
import com.huichenghe.xinlvsh01.DataEntites.CustomRemindEntity;
import com.huichenghe.xinlvsh01.R;
import com.huichenghe.xinlvsh01.Utils.FormatUtils;
import com.huichenghe.xinlvsh01.Utils.LocalDataSaveTool;
import com.huichenghe.xinlvsh01.Utils.MyConfingInfo;

import java.util.ArrayList;

public class RemindActivity extends AppCompatActivity
{
    private CheckBox phoneButton, smsButton;
    private TextView hrSetting;
    private RelativeLayout customLayout;
    private RecyclerView mRecyclerView;
    private RemindCustomRecyclerAdapter mRemindCustomRecyclerAdapter;
    private ArrayList<CustomRemindEntity> dataList;
    private ContentLoadingProgressBar myProgressBar;
    private myRecever recever;
    public static final String TAG = RemindActivity.class.getSimpleName();
    Handler myHandler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remind);
        //设置状态栏和底部功能键
//        settingTheStatebarAndNavigationbar();
        registerRece();

        init();

        checkSwitch();

    }
    // 注册广播
    private void registerRece()
    {
       recever = new myRecever();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MyConfingInfo.CUSTOM_REMIND_VALID);
       registerReceiver(recever, filter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(recever);
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        myProgressBar.show();
        new MyAsycnTask().execute((Void)null);

        myHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
               myProgressBar.hide();
            }
        }, 3000);


    }


    class MyAsycnTask extends AsyncTask<Void, Void, Boolean>
    {

        @Override
        protected Boolean doInBackground(Void... params)
        {
            dataList.clear();
            new BleDataForCustomRemind().getCustomRemind();
            return null;
        }
    }

    /**
     * 检查开关显示的状态
     */
    private void checkSwitch()
    {
        String phone = LocalDataSaveTool.getInstance(RemindActivity.this).readSp(MyConfingInfo.PHONE_REMIND_CHANGE);
        String sms = LocalDataSaveTool.getInstance(RemindActivity.this).readSp(MyConfingInfo.SMS_REMIND_CHANGE);

        if(!phone.isEmpty())
        {
            if(phone.equals(MyConfingInfo.REMIND_OPEN))
            {
                phoneButton.setChecked(true);
            }
            else
            {
                phoneButton.setChecked(false);
            }
        }
        if(!sms.isEmpty())
        {
            if(sms.equals(MyConfingInfo.REMIND_OPEN))
            {
                smsButton.setChecked(true);
            }
            else
            {
                smsButton.setChecked(false);
            }
        }


    }

    private void init()
    {
        myProgressBar = (ContentLoadingProgressBar)findViewById(R.id.myProgressBar);

        dataList = new ArrayList<CustomRemindEntity>();
        mRemindCustomRecyclerAdapter = new RemindCustomRecyclerAdapter(RemindActivity.this, dataList);
        mRecyclerView = (RecyclerView)findViewById(R.id.recycler_layout_show_remind);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(RemindActivity.this));
        mRecyclerView.setAdapter(mRemindCustomRecyclerAdapter);



        customLayout = (RelativeLayout)findViewById(R.id.custom_layout);
        customLayout.setOnClickListener(listener);
        hrSetting = (TextView)findViewById(R.id.hr_remind_setting);
        hrSetting.setOnClickListener(listener);

        phoneButton = (CheckBox)findViewById(R.id.phone_remind_switch);
        smsButton = (CheckBox)findViewById(R.id.sms_remind_switch);
        phoneButton.setOnCheckedChangeListener(checkListener);
        smsButton.setOnCheckedChangeListener(checkListener);




        Toolbar toolbar = (Toolbar)findViewById(R.id.Remind_toolbar);
        toolbar.setTitle(getString(R.string.setting_remind));
        toolbar.setTitleTextColor(getResources().getColor(R.color.White_forme));
        setSupportActionBar(toolbar);

        // 显示返回键
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // 修改返回键图标
        toolbar.setNavigationIcon(R.drawable.back);

        // 返回键监听
        toolbar.setNavigationOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                RemindActivity.this.onBackPressed();

            }
        });
        Log.i("", "Navigation" + toolbar.getNavigationContentDescription());
    }

    private void settingTheStatebarAndNavigationbar() {
        // 透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //底部虚拟键透明
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }


    View.OnClickListener listener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {
                case R.id.hr_remind_setting:

                    break;
                case R.id.custom_layout:
                    byte[] bytess = new byte[dataList.size()];

                    for (int i = 0; i < dataList.size(); i ++)
                    {
                        CustomRemindEntity en = dataList.get(i);
                        byte aa = en.getNumber();     // 获取提醒编号
                        bytess[i] = aa;

                    }



                    Intent intent = new Intent();
                    intent.setClass(RemindActivity.this, SubCustonRemindActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra(MyConfingInfo.SEND_TO_THE_ACTIVITY, bytess);
                    startActivity(intent);
                    break;
            }
        }
    };


    // 监听checkbox，
    CheckBox.OnCheckedChangeListener checkListener = new CheckBox.OnCheckedChangeListener()
    {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            switch (buttonView.getId())
            {
                case R.id.phone_remind_switch:  // 电话提醒开关状态改变
                    if(isChecked)       // 选择了
                    {
                        LocalDataSaveTool.getInstance(RemindActivity.this).writeSp(MyConfingInfo.PHONE_REMIND_CHANGE, MyConfingInfo.REMIND_OPEN);
                    }
                    else
                    {
                        LocalDataSaveTool.getInstance(RemindActivity.this).writeSp(MyConfingInfo.PHONE_REMIND_CHANGE, MyConfingInfo.REMIND_CLOSE);
                    }


                    break;
                case R.id.sms_remind_switch:
                    if(isChecked)       // 选择了
                    {
                        LocalDataSaveTool.getInstance(RemindActivity.this).writeSp(MyConfingInfo.SMS_REMIND_CHANGE, MyConfingInfo.REMIND_OPEN);
                    }
                    else
                    {
                        LocalDataSaveTool.getInstance(RemindActivity.this).writeSp(MyConfingInfo.SMS_REMIND_CHANGE, MyConfingInfo.REMIND_CLOSE);
                    }
                    break;
            }





        }
    };


    /**
     * 接收自定义提醒数据的广播
     */
    class  myRecever extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            byte[] baseData = intent.getByteArrayExtra(MyConfingInfo.CUSTOM_REMIND_VALID_DATA);
            Log.i(TAG, "自定义提醒数据：" + FormatUtils.bytesToHexString(baseData));
            // 解析数据
            CustomRemindEntity entity = new BleDataForCustomRemind().dealTheValidData(RemindActivity.this, baseData);
            if(entity != null )
            {
                dataList.add(entity);   // 将解析后得到的实体类，添加到实体集合中去
                mRemindCustomRecyclerAdapter.notifyDataSetChanged();
            }
        }
    }





    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }
}
